package com.dankegongyu.lib.common.util;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;

import androidx.annotation.NonNull;

/**
 * 剪贴板
 *
 * @author wupuquan
 * @version 1.0
 * @since 2020/4/13 15:43
 */
public class ClipboardUtils {

    private ClipboardUtils() {
    }

    /**
     * 获取剪切板内容
     */
    @NonNull
    public static String getClipboardContent(Context context) {
        String content = "";
        try {
            ClipboardManager clipboardManager = (ClipboardManager) context.getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData primaryClip = clipboardManager.getPrimaryClip();
            if (primaryClip != null && primaryClip.getItemCount() > 0) {
                ClipData.Item itemAt = primaryClip.getItemAt(0);
                if (itemAt != null) {
                    content = itemAt.getText().toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 放置内容发到剪切板
     */
    public static void setClipboardContent(Context context, String content) {
        try {
            ClipboardManager clipboardManager = (ClipboardManager) context.getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData primaryClip = ClipData.newPlainText("Label", content); // 纯文本内容
            clipboardManager.setPrimaryClip(primaryClip);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
